<template>
  <div class="fenbi-question-container">
    <el-breadcrumb separator="/" style="margin-bottom: 18px;">
      <el-breadcrumb-item @click="goBack" style="cursor:pointer;">
        <el-icon><ArrowLeft /></el-icon> 我的收藏
      </el-breadcrumb-item>
      <el-breadcrumb-item>收藏夹</el-breadcrumb-item>
      <el-breadcrumb-item>收藏题目</el-breadcrumb-item>
    </el-breadcrumb>
    <div v-if="questions.length === 0" class="empty-tip">暂无收藏题目</div>
    <div v-else>
      <div class="question-header" style="position:relative;">
        <div class="header-left">
        </div>
        <div class="header-right">
          <el-tag>{{ currentQuestion.course_name }}</el-tag>
          <el-tag>{{ currentQuestion.point_name }}</el-tag>
        </div>
        <el-button
          class="favorite-btn"
          :type="isCollected ? 'warning' : 'info'"
          circle
          @click="toggleCollect"
          :title="isCollected ? '取消收藏' : '收藏本题'"
          v-if="questions.length > 0"
          style="position:absolute;top:-40px;right:0;z-index:10;"
        >
          <el-icon :size="22">
            <StarFilled v-if="isCollected" />
            <Star v-else />
          </el-icon>
        </el-button>
      </div>
      <div class="question-content" v-if="questions.length > 0">
        <!-- 题目序号和类型 -->
        <div class="question-meta">
          <el-tag :type="currentQuestion.type === 'choice' ? 'primary' : 'success'" size="small">
            {{ currentQuestion.type === 'choice' ? '主观题' : '客观题' }}
          </el-tag>
          <span class="question-index">第{{ currentIndex + 1 }}题/共{{ questions.length }}题</span>
          <el-tag type="warning" size="small" v-if="currentQuestion.difficulty">
            难度: {{ getDifficultyText(currentQuestion.difficulty) }}
          </el-tag>
        </div>
        <!-- 题干内容 -->
        <div class="question-text" v-html="currentQuestion.question_content"></div>
        <!-- 选择题选项（粉笔风格） -->
        <div class="question-options" v-if="currentQuestion.type === 'choice'">
          <div class="option-list">
            <div
              v-for="option in currentQuestion.options"
              :key="option.value"
              :class="[
                'option-box',
                userAnswer === option.value ? (showAnalysis
                  ? (isCorrect ? 'selected-correct' : 'selected-wrong')
                  : 'selected') : '',
                showAnalysis && currentQuestion.correctAnswer === option.value ? 'correct-answer' : '',
                showAnalysis ? 'disabled' : ''
              ]"
              @click="!showAnalysis && selectOption(option.value)"
            >
              <span class="option-label">{{ option.label }}</span>
              <span class="option-content" v-html="option.text"></span>
            </div>
          </div>
        </div>
        <!-- 客观题作答区域 -->
        <div class="subjective-answer" v-else>
          <el-input
            type="textarea"
            :rows="4"
            v-model="userAnswer"
            placeholder="请输入您的答案"
            resize="none"
            :disabled="showAnalysis"
          />
        </div>
      </div>
      <div class="question-actions">
        <el-button @click="prevQuestion" :disabled="currentIndex === 0" icon="ArrowLeft">上一题</el-button>
        <el-button @click="nextQuestion" :disabled="currentIndex === questions.length - 1" icon="ArrowRight">下一题</el-button>
        <el-button type="primary" @click="checkAnswer" :disabled="showAnalysis">提交</el-button>
        <el-button v-if="showAnalysis" @click="rePractice">再做一次</el-button>
      </div>
      <!-- 答案和解析区域 -->
      <div class="answer-analysis" v-if="showAnalysis">
        <div class="result-message" :class="isCorrect ? 'correct' : 'wrong'">
          <el-icon :color="isCorrect ? '#67C23A' : '#F56C6C'">
            <CircleCheckFilled v-if="isCorrect" />
            <CircleCloseFilled v-else />
          </el-icon>
          {{ isCorrect ? '回答正确' : '回答错误' }}
        </div>

        <div class="correct-answer">
          <span class="label">正确答案：</span>
          <span class="value" v-html="currentQuestion.correctAnswer"></span>
        </div>

        <div class="user-answer">
          <span class="label">您的答案：</span>
          <span class="value" v-html="userAnswer || '未作答'" ></span>
        </div>

        <div class="analysis-section" v-if="currentQuestion.analysis">
          <div class="section-title">解析</div>
          <div class="section-content" v-html="currentQuestion.analysis"></div>
        </div>

        <div class="knowledge-section" v-if="currentQuestion.point_name">
          <div class="section-title">考点</div>
          <div class="section-content">{{ currentQuestion.point_name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'
import { ElMessage } from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled, ArrowLeft, StarFilled, Star } from '@element-plus/icons-vue'
const route = useRoute()
const router = useRouter()

const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId)

const questions = ref<any[]>([])
const currentIndex = ref(0)
const userAnswer = ref('')
const showAnalysis = ref(false)
const isCorrect = ref(false)
const isCollected = ref(false)

const currentQuestion = computed(() => questions.value[currentIndex.value] || {})

const selectOption = (val: string) => {
  if (showAnalysis.value) return
  userAnswer.value = val
}

const getDifficultyText = (level: number) => {
  const levels = ['简单', '中等', '困难', '极难']
  return levels[level - 1] || '未知'
}

const checkAnswer = () => {
  if (!userAnswer.value) {
    ElMessage.warning('请先作答再提交')
    return
  }
  if (!currentQuestion.value.correctAnswer) {
    ElMessage.error('题目无标准答案，无法判分')
    return
  }
  showAnalysis.value = true
  if (currentQuestion.value.type === 'choice') {
    isCorrect.value = userAnswer.value === currentQuestion.value.correctAnswer
  } else {
    isCorrect.value = userAnswer.value.trim() === (currentQuestion.value.correctAnswer ? String(currentQuestion.value.correctAnswer).trim() : '')
  }
}

const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
    resetQuestionState()
  }
}
const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
    resetQuestionState()
  }
}
const rePractice = () => {
  resetQuestionState()
}
function resetQuestionState() {
  userAnswer.value = ''
  showAnalysis.value = false
  isCorrect.value = false
}
const goBack = () => { router.go(-1) }

function optionClass(val: string) {
  if (!showAnalysis.value) return { 'option-box': true, selected: userAnswer.value === val }
  if (userAnswer.value === val && userAnswer.value === currentQuestion.value.correctAnswer) {
    return { 'option-box': true, 'selected-correct': true }
  }
  if (userAnswer.value === val && userAnswer.value !== currentQuestion.value.correctAnswer) {
    return { 'option-box': true, 'selected-wrong': true }
  }
  if (val === currentQuestion.value.correctAnswer) {
    return { 'option-box': true, 'correct-answer': true }
  }
  return { 'option-box': true }
}

const loadQuestions = async () => {
  const ids = route.query.favoriteId
  const idArray = typeof ids === 'string' ? ids.split(',') : ids
  if (!idArray || idArray.length === 0) {
    ElMessage.error('缺少收藏题ID参数')
    return
  }
  try {
    const res = await axios.get('http://localhost:8080/favorites/byids', {
      params: { ids: (idArray ?? []).join(',') }
    })
    questions.value = res.data || []
    resetQuestionState()
  } catch (e) {
    ElMessage.error('获取题目失败')
  }
}

// 检查当前题目是否已收藏
const checkCollected = async () => {
  const q = currentQuestion.value
  if (!q || !q.question_id || !userId.value) {
    isCollected.value = false
    return
  }
  try {
    const res = await axios.get('http://localhost:8080/favorites/exists', {
      params: { userId: userId.value, questionId: q.question_id }
    })
    isCollected.value = !!res.data
  } catch (e) {
    isCollected.value = false
  }
}

// 收藏/取消收藏
const toggleCollect = async () => {
  const q = currentQuestion.value
  if (!q || !q.question_id || !userId.value) return
  if (isCollected.value) {
    // 取消收藏
    await axios.get('http://localhost:8080/favorites/deletebyuq', {
      params: { userId: userId.value, questionId: q.question_id }
    })
    isCollected.value = false
    ElMessage.success('已取消收藏')
  } else {
    await axios.post('http://localhost:8080/favorites/add', {
      userId: userId.value,
      questionId: q.question_id
    })
    isCollected.value = true
    ElMessage.success('已收藏')
  }
}

// 切题时自动检测收藏状态
watch([currentIndex, questions], () => {
  checkCollected()
})
// 初始加载后检测
onMounted(() => {
  checkCollected()
  loadQuestions()
})
</script>

<style scoped lang="scss">
.option-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
  margin-bottom: 30px;
}
.option-box {
  display: flex;
  align-items: center;
  padding: 18px 22px;
  border-radius: 10px;
  border: 2px solid #ebeef5;
  background: #fff;
  cursor: pointer;
  font-size: 17px;
  margin-bottom: 0;
  transition: all 0.18s cubic-bezier(.4,0,.2,1);
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  user-select: none;
  position: relative;
  min-height: 48px;
}
.option-box:not(.disabled):hover {
  border-color: #409EFF;
  background: #f5faff;
  box-shadow: 0 4px 16px rgba(64,158,255,0.08);
}
.option-box.selected {
  border-color: #409EFF;
  background: #e6f7ff;
  box-shadow: 0 0 0 2px #409EFF22;
}
.option-box.selected-correct {
  border-color: #67C23A;
  background: #f0f9eb;
  box-shadow: 0 0 0 2px #67C23A33;
}
.option-box.selected-wrong {
  border-color: #F56C6C;
  background: #fef0f0;
  box-shadow: 0 0 0 2px #F56C6C33;
}
.option-box.correct-answer {
  border-color: #67C23A;
  background: #f0f9eb;
  box-shadow: 0 0 0 2px #67C23A33;
}
.option-box.disabled {
  cursor: not-allowed;
  opacity: 0.85;
  pointer-events: none;
}
.option-label {
  display: inline-block;
  width: 36px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  font-weight: bold;
  font-size: 19px;
  color: #409EFF;
  background: #e6f7ff;
  border-radius: 50%;
  margin-right: 20px;
  box-shadow: 0 1px 4px #e6f7ff99;
  flex-shrink: 0;
}
.option-box.selected .option-label {
  background: #409EFF;
  color: #fff;
}
.option-box.selected-correct .option-label,
.option-box.correct-answer .option-label {
  background: #67C23A;
  color: #fff;
}
.option-box.selected-wrong .option-label {
  background: #F56C6C;
  color: #fff;
}
.option-content {
  flex: 1;
  color: #303133;
  font-size: 17px;
  word-break: break-all;
}

.fenbi-question-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 28px 18px 22px 18px;
  background: linear-gradient(120deg, #f6fbff 0%, #e3f0ff 100%);
  border-radius: 32px;
  box-shadow: 0 8px 32px 0 rgba(99, 143, 255, 0.12);
}


.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 18px;
  border-bottom: 1px solid #fafafa;
  margin-bottom: 24px;
  .header-left {
    .el-breadcrumb-item {
      cursor: pointer;
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
  .header-right {
    display: flex;
    align-items: center;
    .el-button {
      padding: 0 12px;
      margin-left: 10px;
      border-radius: 18px;
      font-size: 14px;
      background: linear-gradient(90deg, #4ea1e9);
      color: #5b80e6;
      border: none;
      box-shadow: 0 2px 8px 0 rgba(224, 108, 159, 0.10);
      transition: background 0.2s, color 0.2s, transform 0.2s;
      &:hover {
        background: linear-gradient(90deg, #e3f0ff 0%, #bdecf9 100%);
        color: #6cb1e0;
        transform: scale(1.08) rotate(-2deg);
      }
    }
  }
}

.question-meta {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
  .question-index {
    color: #606266;
    font-size: 14px;
  }
}

.question-text {
  font-size: 16px;
  line-height: 1.8;
  margin-bottom: 25px;
  color: #303133;
}

.question-options {
  margin-bottom: 30px;

  .option-item {
    display: block;
    margin-bottom: 15px;
    padding: 10px 15px;
    border-radius: 4px;
    transition: all 0.3s;
    border: 1px solid #dce5f9;

    &:hover {
      background-color: #8db5f0;
    }

    .option-label {
      font-weight: bold;
      margin-right: 10px;
    }
  }

  :deep(.el-radio__input) {
    display: none;
  }

  :deep(.el-radio__label) {
    padding-left: 0;
  }
}

.subjective-answer {
  margin-bottom: 30px;
}

.answer-analysis {
  margin-top: 32px;
  padding: 24px;
  background: linear-gradient(90deg, #fff 60%, #e3f0ff 100%);
  border-radius: 22px;
  box-shadow: 0 4px 16px 0 rgba(99, 143, 255, 0.10);
  .result-message {
    display: flex;
    align-items: center;
    font-size: 17px;
    font-weight: bold;
    margin-bottom: 18px;
    .el-icon {
      margin-right: 8px;
      font-size: 20px;
    }
    &.correct {
      color: #3ac25a;
    }
    &.wrong {
      color: #f97c7c;
    }
  }
  .correct-answer,
  .user-answer {
    margin-bottom: 15px;
    font-size: 15px;
    .label {
      color: #606266;
      font-weight: bold;
    }
    .value {
      color: #303133;
    }
  }
  .section-title {
    font-weight: bold;
    color: #606266;
    margin: 15px 0 8px 0;
    padding-bottom: 5px;
    border-bottom: 1px dashed #e4e7ed;
  }
  .section-content {
    color: #303133;
    line-height: 1.7;
  }
}

.question-actions {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  gap: 20px;
  .el-button {
    border-radius: 18px;
    font-size: 15px;
    min-width: 90px;
    height: 40px;
    background: linear-gradient(90deg, #f6f8f8 0%, #d9e9fb 100%);
    color: #1d65bd;
    border: none;
    box-shadow: 0 2px 8px 0 rgba(224, 108, 159, 0.10);
    transition: background 0.2s, color 0.2s, transform 0.2s;
    &:hover {
      background: linear-gradient(90deg, #e3f0ff 0%, #e4e1e3 100%);
      color: #ccd3d8;
      transform: scale(1.08) rotate(-2deg);
    }
  }
}

.empty-tip {
  padding: 50px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .fenbi-question-container {
    padding: 15px;
  }

  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;

    .header-right {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .question-actions {
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 120px;
    }
  }
}

// UI增强样式
// 请将下面的样式代码移动到 <style scoped lang="scss"> 内：
.option-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
  margin-bottom: 30px;
}
.option-box {
  display: flex;
  align-items: center;
  padding: 18px 22px;
  border-radius: 10px;
  border: 2px solid #ebeef5;
  background: #fff;
  cursor: pointer;
  font-size: 17px;
  margin-bottom: 0;
  transition: all 0.18s cubic-bezier(.4,0,.2,1);
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  user-select: none;
  position: relative;
  min-height: 48px;
}
.option-box:not(.disabled):hover {
  border-color: #3d8ad7;
  background: #f5faff;
  box-shadow: 0 4px 16px rgba(64,158,255,0.08);
}
.option-box.selected {
  border-color: #388de1;
  background: #e6f7ff;
  box-shadow: 0 0 0 2px #409EFF22;
}
.option-box.selected-correct {
  border-color: #CAEBE2;
  background: #f0f9eb;
  box-shadow: 0 0 0 2px #67C23A33;
}
.option-box.selected-wrong {
  border-color: #eb8668;
  background: #fef0f0;
  box-shadow: 0 0 0 2px #F56C6C33;
}
.option-box.correct-answer {
  border-color: #CAEBE2;
  background: #f0f9eb;
  box-shadow: 0 0 0 2px #67C23A33;
}
.option-box.disabled {
  cursor: not-allowed;
  opacity: 0.85;
  pointer-events: none;
}
.option-label {
  display: inline-block;
  width: 36px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  font-weight: bold;
  font-size: 19px;
  color: #409EFF;
  background: #e6f7ff;
  border-radius: 50%;
  margin-right: 20px;
  box-shadow: 0 1px 4px #e6f7ff99;
  flex-shrink: 0;
}
.option-box.selected .option-label {
  background: #409EFF;
  color: #fff;
}
.option-box.selected-correct .option-label,
.option-box.correct-answer .option-label {
  background: #67C23A;
  color: #fff;
}
.option-box.selected-wrong .option-label {
  background: #F56C6C;
  color: #fff;
}
.option-content {
  flex: 1;
  color: #303133;
  font-size: 17px;
  word-break: break-all;
}

</style>